package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dto.AdUserDto;
import com.heima.model.admin.pojo.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author TheCai
 * @date 2021/5/24 15:39
 **/
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1.校验数据
        if(StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }

        //2. 基于用户名查询用户信息
        LambdaQueryWrapper<AdUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AdUser::getName,dto.getName());

        AdUser user = getOne(lambdaQueryWrapper);
        //3. 如果用户不存在 返回错误
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"查无此人");
        }
        //4. 如果用户存在对比密码
        String password = user.getPassword();
            //4.1需要把用户密码和数据库里的盐拼接在一起

//        DigestUtils.getMd5Digest();
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
        if (!inputPwd.equals(password)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //5.检验用户stats
        if (user.getStatus()!=9){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"您的账号已经被封,建议续费呢");
        }

        //6. 修改用户最近登录时间
        user.setLoginTime(new Date());
        this.updateById(user);
        //7. 生成token
        String token = AppJwtUtil.getToken(user.getId());
        //8. 返回结果,发token,返回user信息,把他们装进map
        Map result =new HashMap();
        result.put("token",token);
        AdUser userVo =new AdUser();
        //原来的在前面,目标在后面
        BeanUtils.copyProperties(user,userVo);
        result.put("user",userVo);

        return ResponseResult.okResult(result);
    }

    /**
     * 后端用户注册
     *
     * @param
     * @return
     */
    @Override
    public ResponseResult register(AdUser adUser) {
        //1.参数校验
        if(StringUtils.isBlank(adUser.getName())
                ||StringUtils.isBlank(adUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户名或者密码不能为空");
        }

        // 业务处理
        // 用户的密码加密规则是：MD5（密码 + salt）
        String salt = RandomStringUtils.randomAlphanumeric(8);
        String password = adUser.getPassword();
        adUser.setPassword(DigestUtils.md5DigestAsHex((password+salt).getBytes()));
        //给一个创造时间
        adUser.setCreatedTime(new Date());
        //合格的状态码
        adUser.setStatus(9);

        adUser.setSalt(salt);
        //新增用户
        this.save(adUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
